package com.glacier.cloud.product.service.impl;

import com.glacier.cloud.product.dao.ProductSkuMapper;
import com.glacier.cloud.product.entity.dataobject.ProductSkuDo;
import com.glacier.cloud.product.entity.dto.cmd.ProductLockItemCmd;
import com.glacier.cloud.product.entity.dto.cmd.ProductStockLockCmd;
import com.glacier.cloud.product.service.ProductService;
import com.glacier.framework.component.exception.BizException;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * date 2024-01-04 16:58
 *
 * @author glacier
 * @version 1.0
 */
@Transactional(readOnly = true)
@Service
public class ProductServiceImpl implements ProductService {
    @Resource
    private ProductSkuMapper productSkuMapper;

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public int lockStock(ProductStockLockCmd command) {
        int updateCount = 0;
        for (ProductLockItemCmd product : command.getProducts()) {
            // 查询库存
            ProductSkuDo productSkuDo = this.productSkuMapper.selectByPrimaryKey(product.getProductSkuId());
            if (product.getQuantity() > productSkuDo.getStock() - productSkuDo.getLockStock()) {
                throw new BizException("商品:" + productSkuDo.getId() + "库存不足");
            }
            productSkuDo.setLockStock(productSkuDo.getLockStock() + product.getQuantity());
            updateCount += this.productSkuMapper.updateByPrimaryKey(productSkuDo);
        }
//        int i = 1 / 0;
        return updateCount;
    }
}
